import { useMemo } from "react";
import { useLocation } from "react-router-dom";
import usePermission from "../../hooks/usePermission";
import { RouteConfig } from "../../router/types";

export interface MenuItem {
  key: string;
  title: string;
  path: string;
  icon?: React.ReactNode;
  children?: MenuItem[];
  isActive: boolean;
  isOpen: boolean;
  order: number;
}

/**
 * 菜单管理钩子，根据路由配置和权限生成菜单项
 */
export function useMenuManager(routes: RouteConfig[]) {
  const location = useLocation();
  const permission = usePermission();

  const menuItems = useMemo(() => {
    const buildMenuItems = (
      routes: RouteConfig[],
      parentPath = "",
      level = 0
    ) => {
      // 筛选出有权限访问的路由并排序
      const accessibleRoutes = routes
        .filter(
          (route) =>
            !route.meta?.hideInMenu &&
            permission.canAccess(route) &&
            !route.isLayout
        )
        .sort((a, b) => {
          const orderA = a.meta?.order || 0;
          const orderB = b.meta?.order || 0;
          return orderA - orderB;
        });

      return accessibleRoutes
        .map((route) => {
          const path = `${parentPath}/${route.path}`.replace(/\/+/g, "/");
          const isActive =
            location.pathname === path ||
            location.pathname.startsWith(`${path}/`);

          // 递归构建子菜单
          let children: MenuItem[] = [];
          if (route.children && route.children.length > 0) {
            children = buildMenuItems(route.children, path, level + 1);

            // 如果子菜单为空，且当前路由没有组件，则直接返回null
            if (children.length === 0 && !route.component) {
              return null;
            }
          }

          return {
            key: route.path,
            title: route.meta?.title || route.path,
            path,
            icon: route.meta?.icon,
            children: children.length > 0 ? children : undefined,
            isActive,
            isOpen:
              isActive ||
              (children && children.some((child) => child.isActive)),
            order: route.meta?.order || 0,
            level,
          } as MenuItem;
        })
        .filter(Boolean) as MenuItem[];
    };

    return buildMenuItems(routes);
  }, [routes, location.pathname, permission]);

  // 判断给定路径是否激活
  const isPathActive = (path: string): boolean => {
    return (
      location.pathname === path || location.pathname.startsWith(`${path}/`)
    );
  };

  // 寻找当前活动菜单的所有父菜单路径
  const findActiveMenuPath = (): string[] => {
    const result: string[] = [];

    const findPath = (items: MenuItem[]): boolean => {
      for (const item of items) {
        if (item.isActive) {
          result.push(item.key);
          return true;
        }

        if (item.children && item.children.length) {
          const found = findPath(item.children);
          if (found) {
            result.push(item.key);
            return true;
          }
        }
      }

      return false;
    };

    findPath(menuItems);
    return result.reverse();
  };

  return {
    menuItems,
    isPathActive,
    activeMenuPath: findActiveMenuPath(),
  };
}

export default useMenuManager;
